from datetime import datetime
import hashlib
from flask import json
from exts import db
from sqlalchemy.dialects.mysql import JSON
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy import func
from models.user import AdminUser
from models.warehouse import Warehouse
from services.user_service import *
from services.warehouse_service import *
from services.item_service import *
from services.inventory_service import *

class warehouse_service:

    def get_all_warehouses(self):

        all_Warehouses = Warehouse.query.all()
        # print("all_Warehouses",all_Warehouses)
        if not all_Warehouses:
            return []
        return [
            {
                "id": warehouse.id,  # 将Warehouse改为warehouse
                "name": warehouse.name,
                "location": warehouse.location,
                "created_by": warehouse.created_by,
                "created_name": user_service().get_user_info(warehouse.created_by)["username"],
                
            }
            for warehouse in all_Warehouses  # 将Warehouse改为warehouse
        ]

    def get_id_warehouse(self, id):

        if not id:
            raise Exception("仓库id不能为空")
        warehouse = Warehouse.query.filter_by(id=id).first()
        if not warehouse:
            raise Exception("仓库id不存在")
        return {
            "id": warehouse.id,
            "name": warehouse.name,
            "location": warehouse.location,
            "created_by": warehouse.created_by,
            "created_name": user_service().get_user_info(warehouse.created_by)["username"],
        }

    def exist_warehouse(self, name):

        if not name:
            raise Exception("仓库名称不能为空")
        warehouse = Warehouse.query.filter_by(name=name).first()
        if not warehouse:
            raise Exception("仓库名称不存在")
        return warehouse

    def create_warehouse(self, post_json, created_by):
        if not post_json:
            raise Exception("请输入仓库信息")
        if not post_json.get("name"):
            raise Exception("请输入仓库名称")
        if not post_json.get("location"):
            raise Exception("请输入仓库位置")

        name = post_json.get("name")
        location = post_json.get("location")

        # 使用exist_warehouse检查仓库是否存在
        try:
            self.exist_warehouse(name)
            raise Exception(f"仓库名称 '{name}' 已存在")
        except Exception as e:
            if "不存在" not in str(e):
                raise

        new_warehouse = Warehouse(
            name=name,
            location=location,
            created_by=created_by,
        )
        db.session.add(new_warehouse)
        db.session.commit()
        return self.get_id_warehouse(new_warehouse.id)

    def update_warehouse(self, put_json):
        if put_json:
            id = put_json.get("id",None)
            name = put_json.get("name", None)
            location = put_json.get("location", None)
            created_by = put_json.get("created_by", None)

            if not id:
                raise Exception("仓库ID不能为空")

            if not self.get_id_warehouse(id):
                raise Exception(f"仓库 {id} 不存在")

            warehouse = Warehouse.query.get(id)
            if name:
                warehouse.name = name
            if location:
                warehouse.location = location
            if created_by:
                # 检查用户是否存在
                user = AdminUser.query.filter_by(id=created_by).first()
                if not user:
                    raise Exception(f"用户 ID {created_by} 不存在")
                warehouse.created_by = created_by
            db.session.commit()
            return self.get_id_warehouse(id)
        else:
            raise Exception("请输入仓库信息")

    def delete_warehouse(self, delete_json):
        if delete_json:
            id = delete_json.get("id",None)
            if not id:
                raise Exception("仓库ID不能为空")

            warehouse = Warehouse.query.get(id)
            if not warehouse:
                raise Exception(f"仓库 {id} 不存在")

            # 先获取用户信息保存
            warehouse_info = self.get_id_warehouse(id)

            db.session.delete(warehouse)
            db.session.commit()
            return warehouse_info  # 返回删除前的仓库信息
